﻿namespace CodingExercises._31_40;

public class GetTicTacToeResult
{
    private const char X = 'X';

    // 检查井子棋游戏结果
    public static GameResult Method(char[,] grid)
    {
        if (grid.GetLength(0) != 3 || grid.GetLength(1) != 3)
        {
            throw new ArgumentException("Grid must be 3x3.", nameof(grid));
        }

        GameResult? rowWinner = CheckRows(grid);
        if (rowWinner is not null)
        {
            return rowWinner.Value;
        }

        GameResult? colWinner = CheckColumns(grid);
        if (colWinner is not null)
        {
            return colWinner.Value;
        }

        GameResult? diagonalWinner = CheckDiagonals(grid);
        if (diagonalWinner is not null)
        {
            return diagonalWinner.Value;
        }

        return GameResult.Draw;
    }

    private static GameResult? CheckRows(char[,] grid)
    {
        for (int row = 0; row < 3; row++)
        {
            if (grid[row, 0] == grid[row, 1] &&
                grid[row, 1] == grid[row, 2])
            {
                return grid[row, 0] == X ? GameResult.XWins : GameResult.OWins;
            }
        }

        return null;
    }

    private static GameResult? CheckColumns(char[,] grid)
    {
        for (int col = 0; col < 3; col++)
        {
            if (grid[0, col] == grid[1, col] &&
                grid[1, col] == grid[2, col])
            {
                return grid[0, col] == X ? GameResult.XWins : GameResult.OWins;
            }
        }

        return null;
    }

    private static GameResult? CheckDiagonals(char[,] grid)
    {
        if (grid[0, 0] == grid[1, 1] &&
            grid[1, 1] == grid[2, 2])
        {
            return grid[0, 0] == X ? GameResult.XWins : GameResult.OWins;
        }

        return null;
    }

    public enum GameResult
    {
        Draw,
        XWins,
        OWins
    }
}